package com.kefu.client.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.kefu.client.services.ClientServices;
import com.kefu.model.ClientUser;
import com.kefu.model.LayimFriendInfo;
import com.kefu.model.LayimInitResult;
import com.kefu.model.SystemUser;
import com.kefu.util.Time;

@Controller
@Scope("prototype")
public class ClientUserInit {
	
	public ClientUserInit() {
		System.out.println("Info:init client user init controller...   Time:"+Time.getNowTime());
	}

	@Autowired
	ClientServices clientServices;
	
	@RequestMapping("/init.c")
	public void register(String uid,HttpServletResponse response) throws IOException{
		LayimInitResult result=new LayimInitResult();
		result.setCode(0);
		if(uid==null){
			result.setCode(1001);//设置失败
			result.setMsg("未检测到客户编号");//设置失败事由
		}else{
			//校验用户id是否存在
			if(clientServices.checkClientUid(uid)!=1){
				result.setCode(1002);//设置失败
				result.setMsg("创建会话失败,请刷新页面后重试。 错误-1002");//设置失败事由
			}else{
				//获取在线客服列表
				List<SystemUser> sysUsers=clientServices.findOnLineSystemUsers();
				if(sysUsers==null||sysUsers.size()<1){
					result.setCode(1003);//设置失败
					result.setMsg("客服们都去休息了,请您换个时间再联系好吗？");//设置失败事由
				}else{
					//分配服务人数最少的客服
					SystemUser su=sysUsers.get(0);
					ClientUser cu=clientServices.selectClientUserByUid(uid);
					cu.setState("online");//设置用户在线状态
					if(cu.getIsInit()==null||cu.getIsInit()!=1){
						cu.setIsInit(1);
						cu.setInit_time(Time.getNowTime());
					}
					cu.setSystem_uuid(su.getUuid());
					clientServices.updateClientUserById(cu);
					//给客服服务人数+1
					clientServices.updateSystemCustomUser(su,+1);

					//通过 t-io 向客服端创建新聊天
					//TODO 未实现
					
					//响应给用户端服务的客服信息
					LayimFriendInfo system=new LayimFriendInfo();
					system.setId(su.getUuid());
					system.setAvatar("./lib/imgs/luntan_logo.png");
					system.setUsername(su.getName());
					result.setSystem(system);
				}
				
			}
		}
		String result_json=JSONObject.toJSONString(result);
		//设置响应
		response.setCharacterEncoding("UTF-8");    
		response.setContentType("application/json; charset=utf-8");  
		//返回用户对象
		PrintWriter pw=response.getWriter();
		pw.write(result_json);
		pw.close();
	}
}
